import {replaceObj} from "./temp"
import Cookies from 'js-cookie'
import {getWebConfig,getWebConfigFromLocal,getContext} from "./toml"
import {setStore,getStore} from "./storage"
//
import http from '@/axios';
import get from "lodash/get"
import has from "lodash/has"


export const tokenKey = () => {
  const config = getWebConfigFromLocal();
  const {name,tokenCacheKey} = config;
  return `${name}-${tokenCacheKey}`;
}

export const setToken = (token:string) => {
  const config = getWebConfigFromLocal();
  const {name,tokenCacheKey,cacheTimeout} = config;
  const key = `${name}-${tokenCacheKey}`;
  setStore(key,token)
  Cookies.set(key,token,{expires:new Date(new Date().getTime() + cacheTimeout)})
}

export const getToken = (isDebug = false) => {
  const config = getWebConfigFromLocal();
  const {name,tokenCacheKey} = config;
  const key = `${name}-${tokenCacheKey}`;
  const v1 = getStore(key,isDebug);
  const v2 = Cookies.get(key);
  return v1 || v2;
}

export const setRefreshToken = (token:string) => {
  const config = getWebConfigFromLocal();
  const {name,refreshTokenCacheKey,cacheTimeout} = config;
  const key = `${name}-${refreshTokenCacheKey}`;
  setStore(key,token)
  Cookies.set(key,token,{expires:new Date(new Date().getTime() + cacheTimeout)})
}

export const getRefreshToken = () => {
  const config = getWebConfigFromLocal();
  const {name,refreshTokenCacheKey} = config;
  const key = `${name}-${refreshTokenCacheKey}`;
  const v1 = getStore(key);
  const v2 = Cookies.get(key);
  return v1 || v2;
}

const refresh = async () => {
  const config = getWebConfigFromLocal();
  const {api,path} = config.refreshToken;
  const apiConfig = replaceObj(api,getContext())
  //
  try{
    const res = await http(apiConfig)
    const token = get(res,path.token)
    const refreshToken = get(res,path.refreshToken)
    setToken(token);
    setRefreshToken(refreshToken)
  }catch(e){
    console.log(e)
  }
}

export const refreshToken = async () => {
  const config = await getWebConfig(false);
  const {loopTime = 20000,maxTime = 7200000} = config.refreshToken;
  const token = getToken();
  const key = tokenKey();
  // 是否启用刷新，和判定是否已登录
  if(!token || !config.isRefreshToken) { return ;}
  let lock = false;
  
  setInterval(async () => {
    const {datetime} = getStore(key,true)
    const cd = new Date().getTime() - datetime;
    if(cd > maxTime && !lock){
      // 刷新 token
      lock = true;
      await refresh();
      lock = false;
    }
  },loopTime)
}

// 从对象中获取 token 
export const getObjToken = (obj:any) => {
  const config = getWebConfigFromLocal();
  const {nologin:cfg = {token:"token",refreshToken:"refreshToken"}} = config;
  const res:Record<string,string> = {}
  Object.keys(cfg).forEach(k => {
    const v = cfg[k];
    if(has(obj,v)){
      res[k] = get(obj,v) as string
    }
  })
  return res;
}


export const noLogin = async ({route}:any) => {
  const config = await getWebConfig(false);
  const {nologin} = config;
  if(!nologin) {return ;}
  const res = getObjToken(route.query)
  setToken(res.token);
  setRefreshToken(res.refreshToken);
}

export const initToken = async (config:any) => {
  const t = getToken(true)
  const { refreshToken } = await getWebConfig(false);
  const max = refreshToken.maxTime
  const time = new Date().getTime();
  if(t && time - t.time < max){
    return ;
  }
  noLogin(config);
}

